const express = require('express');
const Article = require('../models/Article');
const { authenticateToken, Authorization } = require('../security');
const { USER_ROLES } = require('../security');
const { cacheMiddleware, clearCache } = require('../cache');

const router = express.Router();

// 获取所有文章
router.get('/articles', cacheMiddleware(300), async (req, res) => {
    try {
        const page = parseInt(req.query.page) || 1;
        const limit = parseInt(req.query.limit) || 10;
        const status = req.query.status;
        
        const filters = {};
        if (status) filters.status = status;
        
        // 权限过滤：非管理员只能看到已发布的文章
        const userRole = req.user?.role || USER_ROLES.GUEST;
        if (userRole !== USER_ROLES.ADMIN) {
            filters.status = 'published';
        }
        
        const result = await Article.findAll(page, limit, filters);
        
        res.json({
            success: true,
            data: {
                articles: result.articles,
                total: result.total,
                page: page,
                limit: limit,
                totalPages: Math.ceil(result.total / limit)
            }
        });
    } catch (error) {
        console.error('获取文章列表失败:', error);
        res.status(500).json({
            success: false,
            message: '获取文章列表失败'
        });
    }
});

// 获取单篇文章
router.get('/articles/:id', cacheMiddleware(600), async (req, res) => {
    try {
        const articleId = parseInt(req.params.id);
        const article = await Article.findById(articleId);
        
        if (!article) {
            return res.status(404).json({
                success: false,
                message: '文章不存在'
            });
        }
        
        // 权限检查：非管理员只能访问已发布的文章
        const userRole = req.user?.role || USER_ROLES.GUEST;
        if (userRole !== USER_ROLES.ADMIN && article.status !== 'published') {
            return res.status(403).json({
                success: false,
                message: '没有权限访问此文章'
            });
        }
        
        res.json({
            success: true,
            data: article
        });
    } catch (error) {
        console.error('获取文章失败:', error);
        res.status(500).json({
            success: false,
            message: '获取文章失败'
        });
    }
});

// 创建文章
router.post('/articles', authenticateToken, Authorization.requirePermission('articles', 'create'), async (req, res) => {
    try {
        const { title, category, theme, keywords, content, status = 'draft' } = req.body;
        
        if (!title || !content) {
            return res.status(400).json({
                success: false,
                message: '标题和内容不能为空'
            });
        }
        
        const article = await Article.create({
            title,
            category: category || 'general',
            theme: theme || '',
            keywords: keywords || '',
            content,
            status,
            authorId: req.user.userId
        });
        
        // 清除缓存
        clearCache('/api/articles');
        
        res.status(201).json({
            success: true,
            message: status === 'published' ? '文章发布成功' : '草稿保存成功',
            data: article
        });
    } catch (error) {
        console.error('创建文章失败:', error);
        res.status(500).json({
            success: false,
            message: '创建文章失败'
        });
    }
});

// 更新文章
router.put('/articles/:id', authenticateToken, Authorization.requirePermission('articles', 'update'), async (req, res) => {
    try {
        const articleId = parseInt(req.params.id);
        const article = await Article.findById(articleId);
        
        if (!article) {
            return res.status(404).json({
                success: false,
                message: '文章不存在'
            });
        }
        
        // 权限检查：只能更新自己的文章，除非是管理员
        if (article.authorId !== req.user.userId && req.user.role !== USER_ROLES.ADMIN) {
            return res.status(403).json({
                success: false,
                message: '没有权限更新此文章'
            });
        }
        
        const updatedArticle = await article.update(req.body);
        
        // 清除缓存
        clearCache('/api/articles');
        clearCache(`/api/articles/${articleId}`);
        
        res.json({
            success: true,
            message: '文章更新成功',
            data: updatedArticle
        });
    } catch (error) {
        console.error('更新文章失败:', error);
        res.status(500).json({
            success: false,
            message: '更新文章失败'
        });
    }
});

// 删除文章（移至回收站）
router.delete('/articles/:id', authenticateToken, Authorization.requirePermission('articles', 'delete'), async (req, res) => {
    try {
        const articleId = parseInt(req.params.id);
        const article = await Article.findById(articleId);
        
        if (!article) {
            return res.status(404).json({
                success: false,
                message: '文章不存在'
            });
        }
        
        // 权限检查：只能删除自己的文章，除非是管理员
        if (article.authorId !== req.user.userId && req.user.role !== USER_ROLES.ADMIN) {
            return res.status(403).json({
                success: false,
                message: '没有权限删除此文章'
            });
        }
        
        await article.update({ status: 'deleted' });
        
        // 清除缓存
        clearCache('/api/articles');
        
        res.json({
            success: true,
            message: '文章已移至回收站'
        });
    } catch (error) {
        console.error('删除文章失败:', error);
        res.status(500).json({
            success: false,
            message: '删除文章失败'
        });
    }
});

// 发布文章
router.put('/articles/:id/publish', authenticateToken, Authorization.requirePermission('articles', 'update'), async (req, res) => {
    try {
        const articleId = parseInt(req.params.id);
        const article = await Article.findById(articleId);
        
        if (!article) {
            return res.status(404).json({
                success: false,
                message: '文章不存在'
            });
        }
        
        // 权限检查：只能发布自己的文章，除非是管理员
        if (article.authorId !== req.user.userId && req.user.role !== USER_ROLES.ADMIN) {
            return res.status(403).json({
                success: false,
                message: '没有权限发布此文章'
            });
        }
        
        await article.update({ status: 'published' });
        
        // 清除缓存
        clearCache('/api/articles');
        
        res.json({
            success: true,
            message: '文章发布成功'
        });
    } catch (error) {
        console.error('发布文章失败:', error);
        res.status(500).json({
            success: false,
            message: '发布文章失败'
        });
    }
});

// 恢复文章
router.put('/articles/:id/restore', authenticateToken, Authorization.requirePermission('articles', 'update'), async (req, res) => {
    try {
        const articleId = parseInt(req.params.id);
        const article = await Article.findById(articleId);
        
        if (!article) {
            return res.status(404).json({
                success: false,
                message: '文章不存在'
            });
        }
        
        // 权限检查：只能恢复自己的文章，除非是管理员
        if (article.authorId !== req.user.userId && req.user.role !== USER_ROLES.ADMIN) {
            return res.status(403).json({
                success: false,
                message: '没有权限恢复此文章'
            });
        }
        
        await article.update({ status: 'draft' });
        
        // 清除缓存
        clearCache('/api/articles');
        
        res.json({
            success: true,
            message: '文章已恢复'
        });
    } catch (error) {
        console.error('恢复文章失败:', error);
        res.status(500).json({
            success: false,
            message: '恢复文章失败'
        });
    }
});

// 永久删除文章
router.delete('/articles/:id/permanent', authenticateToken, Authorization.requirePermission('articles', 'delete'), async (req, res) => {
    try {
        const articleId = parseInt(req.params.id);
        const article = await Article.findById(articleId);
        
        if (!article) {
            return res.status(404).json({
                success: false,
                message: '文章不存在'
            });
        }
        
        // 权限检查：只能永久删除自己的文章，除非是管理员
        if (article.authorId !== req.user.userId && req.user.role !== USER_ROLES.ADMIN) {
            return res.status(403).json({
                success: false,
                message: '没有权限永久删除此文章'
            });
        }
        
        await Article.delete(articleId);
        
        // 清除缓存
        clearCache('/api/articles');
        
        res.json({
            success: true,
            message: '文章已永久删除'
        });
    } catch (error) {
        console.error('永久删除文章失败:', error);
        res.status(500).json({
            success: false,
            message: '永久删除文章失败'
        });
    }
});

// 搜索文章
router.get('/articles/search', cacheMiddleware(300), async (req, res) => {
    try {
        const query = req.query.q;
        const page = parseInt(req.query.page) || 1;
        const limit = parseInt(req.query.limit) || 10;
        
        if (!query || query.trim() === '') {
            return res.status(400).json({
                success: false,
                message: '搜索关键词不能为空'
            });
        }
        
        const result = await Article.search(query, page, limit);
        
        res.json({
            success: true,
            data: {
                articles: result.articles,
                total: result.total,
                page: page,
                limit: limit,
                totalPages: Math.ceil(result.total / limit)
            }
        });
    } catch (error) {
        console.error('搜索文章失败:', error);
        res.status(500).json({
            success: false,
            message: '搜索文章失败'
        });
    }
});

module.exports = router;